package com.longan.web.controller.common;

import com.longan.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/out")
public class BigFileController {

    @Value("${ruoyi.profile}")
    private String filePath;

    @Value("${host.url}")
    private String localhost;

    @GetMapping("/host")
    public AjaxResult host() {
        Map<String,String> map = new HashMap<>();
        map.put("url",localhost);
        return AjaxResult.success(map);
    }


    @PostMapping("/upload/chunk")
    public String uploadChunk(@RequestParam("file") MultipartFile file,
                              @RequestParam("identifier") String identifier,
                              @RequestParam("chunkNumber") int chunkNumber) {
        try {
            File chunkDir = new File(filePath + File.separator + identifier);
            if (!chunkDir.exists()) {
                chunkDir.mkdirs();
            }
            File chunkFile = new File(chunkDir, "chunk_" + chunkNumber);
            file.transferTo(chunkFile);
            return localhost + "/" + file.getName();
        } catch (IOException e) {
            e.printStackTrace();
            return "Chunk upload failed";
        }
    }

    @PostMapping("/upload/merge")
    public String mergeChunks(@RequestParam("identifier") String identifier,
                              @RequestParam("filename") String filename) {
        try {
            File chunkDir = new File(filePath + File.separator + identifier);
            File[] chunks = chunkDir.listFiles();
            if (chunks == null) {
                return "No chunks found";
            }
            List<File> sortedChunks = new ArrayList<>(Arrays.asList(chunks));
            sortedChunks.sort((f1, f2) -> {
                int num1 = Integer.parseInt(f1.getName().split("_")[1]);
                int num2 = Integer.parseInt(f2.getName().split("_")[1]);
                return Integer.compare(num1, num2);
            });
            File mergedFile = new File(filePath + File.separator + filename);
            try (FileOutputStream fos = new FileOutputStream(mergedFile)) {
                for (File chunk : sortedChunks) {
                    try (FileInputStream fis = new FileInputStream(chunk)) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = fis.read(buffer)) != -1) {
                            fos.write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
            // 删除临时分片文件
            for (File chunk : sortedChunks) {
                chunk.delete();
            }
            chunkDir.delete();
            return localhost + "/out/download/" + filename;
        } catch (IOException e) {
            e.printStackTrace();
            return "Chunk merge failed";
        }
    }

    @GetMapping("/download/{filename}")
    public void downloadFile(@PathVariable String filename, HttpServletResponse response) {
        try {
            Path file = Paths.get(filePath, filename);
            System.out.println(file.getParent());
            System.out.println(filename);
            if (Files.exists(file)) {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);
                Files.copy(file, response.getOutputStream());
                response.getOutputStream().flush();
            }
            System.out.println("文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/files")
    public List<String> listFiles() {
        File uploadDir = new File(filePath);
        File[] files = uploadDir.listFiles();
        List<String> fileNames = new ArrayList<>();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    fileNames.add(file.getName());
                }
            }
        }
        return fileNames;
    }
}
